/*
 * $Id: SubmitAction.java 23 2002-09-29 13:59:30Z bpruessmann $
 * 
 * Copyright (c) 2001,2002 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 */
package net.sourceforge.p4eclipse.ui.action;

import java.util.ArrayList;
import java.util.Iterator;

import net.sourceforge.p4eclipse.core.PerforceException;
import net.sourceforge.p4eclipse.core.PerforceSynchronizerRunnable;
import net.sourceforge.p4eclipse.core.api.IChangesResult;
import net.sourceforge.p4eclipse.core.api.IInfoResult;
import net.sourceforge.p4eclipse.core.api.IWhereResult;
import net.sourceforge.p4eclipse.ui.PerforceUIPlugin;
import net.sourceforge.p4eclipse.ui.dialogs.ChangeSpecDialog;
import net.sourceforge.p4eclipse.ui.views.PendingChangelistView;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ui.actions.TeamAction;

/**
  * @version 	$Revision: 23 $
  * @author		<a href="mailto:bpruessmann@users.sourceforge.net">Boris Pruessmann</a>
  */
public class SubmitAction extends TeamAction
{
	/** @see IActionDelegate#run(IAction) */
	public void run(IAction action)
	{
		IChangesResult[] changesResults = getSelectedChangesResult();	
		try
		{
			ChangeSpecDialog dialog = ChangeSpecDialog.newChangeSpecDialog(getShell(), changesResults[0].getChangelist());
			if (dialog.open() == ChangeSpecDialog.OK)
			{
				String changeSpecString = dialog.getChangeSpecString();
				try
				{				
					String[] changedFiles = 
						PerforceUIPlugin.getClient().submit(changeSpecString);
					
					PerforceSynchronizerRunnable.wakeup();
					PendingChangelistView.getInstance().refreshClientChangelists();
					
					NullProgressMonitor progress = new NullProgressMonitor();
					IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
					for (int i = 0, length = changedFiles.length; i < length; i++)
					{
						IWhereResult whereResult =
							PerforceUIPlugin.getClient().where(changedFiles[i]);
							
						IFile file = root.getFileForLocation(
							new Path(whereResult.getLocalFilename()));
						file.refreshLocal(IResource.DEPTH_ZERO, progress);
					}											
				}
				catch (CoreException e)
				{
					ErrorDialog.openError(getShell(), "Perforce Error", e.getStatus().getMessage(), e.getStatus());

				}
				catch (PerforceException e)
				{
					ErrorDialog.openError(getShell(), "Perforce Error", "A Perforce operation failed.", e.getStatus());
				}
			}
		}
		catch (PerforceException e)
		{
			ErrorDialog.openError(getShell(), "Perforce Error", "SubmitAction failed.", e.getStatus());
		}
	}

	/** @see TeamAction#isEnabled() */
	protected boolean isEnabled()
		throws TeamException
	{
		IChangesResult[] changesResults = getSelectedChangesResult();
		if (changesResults.length != 1)
			return false;
			
		IInfoResult infoResult = PerforceUIPlugin.getClient().info();
		if (!(infoResult.getClientName().equals(changesResults[0].getClientName())))
			return false;
			
		return true;
	}
	
	/**
	  * Returns an array of all selected IChangesResult objects.
	  */
	private IChangesResult[] getSelectedChangesResult()
	{
		ArrayList resources = null;
		if (!selection.isEmpty())
		{
			resources = new ArrayList();
			for (Iterator elements = ((IStructuredSelection)selection).iterator(); elements.hasNext(); )
			{
				Object next = elements.next();
				
				if (next instanceof IChangesResult)
				{
					resources.add(next);
					continue;
				}
				else
				if (next instanceof IAdaptable)
				{
					IAdaptable a = (IAdaptable) next;
					Object adapter = a.getAdapter(IChangesResult.class);
					if (adapter instanceof IChangesResult)
					{
						resources.add(adapter);
						continue;
					}
				}
			}
		}
		
		if (resources != null && !resources.isEmpty())
		{
			IChangesResult[] result = new IChangesResult[resources.size()];
			resources.toArray(result);
			return result;
		}
		
		return new IChangesResult[0];
	}	
}
